﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HubbleTelescope.Framework;
using HubbleTelescope.Model;
using System.Windows.Input;

namespace HubbleTelescope.Controllers
{
    /// <summary>
    /// Controller that coordinates work to the Telescope Model
    /// </summary>
    public sealed class TelescopeController : PropertyChangedBase
    {
        //Create our Model class for use
        private Telescope _telescope = new Telescope();

        #region Properties exposed to View

        private string _title = "Hubble Space Telescope";

        /// <summary>
        /// The title of the window
        /// </summary>
        public string Title
        {
            get { return _title; }
            set { _title = value; OnPropertyChanged("Title"); }
        }

        private Planet[] _planets = null;

        /// <summary>
        /// List of planets
        /// </summary>
        public Planet[] Planets
        {
            get { return _planets; }
            set { _planets = value; OnPropertyChanged("Planets"); }
        }

        /// <summary>
        /// Command that refreshes the Planets property
        /// </summary>
        public DelegateCommand Refresh
        {
            get;
            private set;
        }

        private bool _isBusy = false;

        /// <summary>
        /// Indicates a search is in progress
        /// </summary>
        public bool IsBusy
        {
            get { return _isBusy; }
            set { _isBusy = value; OnPropertyChanged("IsBusy"); OnPropertyChanged("IsNotBusy"); }
        }

        /// <summary>
        /// Indicates a search is not in progress
        /// </summary>
        public bool IsNotBusy
        {
            get { return !_isBusy; }
        }

        #endregion

        public TelescopeController()
        {
            //Setup our Refresh command
            Refresh = new DelegateCommand(() =>
            {
                Planets = null;
                IsBusy = true;
                _telescope.MeasurePlanets();
                Refresh.InvalidateCanExecute();
            },
            () => !IsBusy);

            //Hook up the event from our Model
            _telescope.PlanetsMeasured += (sender, e) =>
            {
                //We need to execute on the main thread, since the Telescope class works on a background thread
                Execute.OnUIThread(() =>
                {
                    IsBusy = false;
                    Planets = e.Planets;
                    Refresh.InvalidateCanExecute();
                });
            };
        }
    }
}
